package com.jsyl.lwbk.business.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jsyl.lwbk.business.constant.ProjectCodeConstant;
import com.jsyl.lwbk.business.domain.*;
import com.jsyl.lwbk.business.domain.education.ChildCourse;
import com.jsyl.lwbk.business.domain.education.ChildCourseExample;
import com.jsyl.lwbk.business.dto.*;
import com.jsyl.lwbk.business.handle.AliOssHandle;
import com.jsyl.lwbk.business.mapper.*;
import com.jsyl.lwbk.business.mapper.education.ChildCourseMapper;
import com.jsyl.lwbk.business.mapper.education.CourseChildMapper;
import com.jsyl.lwbk.business.service.IntegrationService;
import com.jsyl.lwbk.business.service.PrepareClassService;
import com.jsyl.lwbk.common.constant.Constants;
import com.jsyl.lwbk.common.exception.BusinessException;
import com.jsyl.lwbk.common.utils.AgeUtils;
import com.jsyl.lwbk.common.utils.DateUtils;
import com.jsyl.lwbk.common.utils.StringUtils;
import com.jsyl.lwbk.common.utils.pdf.HtmlToPdf1Utils;
import com.jsyl.lwbk.system.domain.SysRole;
import com.jsyl.lwbk.system.domain.SysUser;
import com.jsyl.lwbk.system.utils.DictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.IsoFields;
import java.util.*;

/**
 * @author Fitch
 * 2022/3/2
 */
@Service
public class PrepareClassServiceImpl implements PrepareClassService {
    @Autowired
    AliOssHandle aliOssHandle;
    @Autowired
    private ChildCourseMapper childCourseMapper;
    @Autowired
    private ReadingComprehensionPlanMapper readingComprehensionPlanMapper;
    @Autowired
    private ClassPlanSortMapper classPlanSortMapper;
    @Autowired
    private ClassPlanMapper classPlanMapper;
    @Autowired
    private ClassPlanDetailMapper classPlanDetailMapper;
    @Autowired
    private ChildProjectConfigMapper childProjectConfigMapper;
    @Autowired
    private InitRule initRule;
    @Autowired
    private CourseChildProjectMapper courseChildProjectMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IntegrationService integrationService;
    @Autowired
    private IntegrationTrainAmountMapper integrationTrainAmountMapper;
    @Autowired
    private TrainPackageMapper trainPackageMapper;
    @Autowired
    private CourseTrainPackageMapper courseTrainPackageMapper;
    @Autowired
    private CourseChildMapper courseChildMapper;
    @Autowired
    private CourseChildScoreMapper courseChildScoreMapper;
    @Autowired
    private IntegrationMapper integrationMapper;
//    @Autowired
//    private SchedulePrepareSender sender;

    @Override
    public List<ChildCourse> list(ChildCourseDTO dto, SysUser sysUser) {
        if (dto.getCenterId() == null) {
            throw new BusinessException("请选择中心。");
        }
        ChildCourseExample example = new ChildCourseExample();
        if (dto.getScheduleTime() == null || dto.getScheduleTime() == "") {
            dto.setScheduleTime(DateUtils.getDate());
        }
        ChildCourseExample.Criteria criteria = example.createCriteria();
        criteria.andDayDateEqualTo(dto.getScheduleTime());
        criteria.andCenterIdEqualTo(dto.getCenterId());
        if (dto != null && dto.getTeacherName() != null && dto.getTeacherName() != "") {
            criteria.andTeacherNameLike(dto.getTeacherName());
        }
        //只有校区老师角色只看他自己课程
        boolean temp =true;
        if(sysUser !=null){
            for(SysRole role:sysUser.getRoles()){
                if(!role.getRoleKey().equals("teacher")){
                    temp=false;
                }
            }
            if(!temp){
                dto.setTeacherId(null);
            }
        }
        List<ChildCourse> childCourses = childCourseMapper.selectList(dto.getScheduleTime(), String.valueOf(dto.getCenterId()), dto.getTeacherName(),dto.getTeacherId());
        Map<String,String> existTips=new HashMap<>();
        for (ChildCourse c : childCourses) {
            c.setChildInfoDTOList(this.childCourseMapper.listChildInfo(c.getId()));
            c.setWeekDay(DateUtils.getWeekDay(DateUtils.parseDate(dto.getScheduleTime())));
            //是否显示未上课：（1）当前课程已备课   （2）当前时间≥课程的下课时间。
            if (c.getPrepareStatus().equals(1) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate())) {
                c.setShowNotClass(1);
            }
            //是否显示取消备课：（1）当前课程已备课 （2）当前时间≥课程的上课课时间。
            if (c.getPrepareStatus().equals(1) && DateUtils.getNowDate().before(DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()))) {
                c.setShowCancelClass(1);
            }
            //1-未上课，2-上课中，3-已上课，4-已过期
            //当前时间≥课程的上课时间
            if (( DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()).after(DateUtils.getNowDate()))) {
                c.setCourseStatus(1);
            }
            //当前时间≥课程的上课时间 AND 当前时间<=课程的下课时间。
            if ( DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()).before(DateUtils.getNowDate())
                    && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).after(DateUtils.getNowDate())) {
                c.setCourseStatus(2);
            }
            //已备课且课程时间已过，显示已上课
            if (c.getPrepareStatus().equals(1) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate())) {
                c.setCourseStatus(3);
            }
            //未备课且课程时间已经开始，显示已过期
            if (c.getPrepareStatus().equals(2) ||(c.getPrepareStatus().equals(0) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate()))) {
                c.setCourseStatus(4);
//                c.setCourseTips("课程过期，无法备课！");
            }
            for(ChildInfoDTO cif:c.getChildInfoDTOList()){
                cif.setAge(AgeUtils.buildAge(cif.getBirthYear(),cif.getBirthMonth(),cif.getBirthDay()));
                cif.setGrade(AgeUtils.getGrade(StringUtils.getInt(cif.getGrade())));
//                if(cif.getPrepareStatus().equals(1) && cif.getChildProjectId() ==null){
//                    c.setCourseTips("该班级有新增学员，请及时完成新学员备课！");
//                }
            }
//            if(!c.getCourseStatus().equals(4)){
//                //查看本班级上节课是否已填写成绩
//                ChildCourse childCourse = this.childCourseMapper.getLastClassScoreFlag(c.getClassId(),c.getDayDate()+" "+c.getStartTime(),c.getDayDate());
//                if(childCourse!=null && childCourse.getPrepareStatus().equals(1) && childCourse.getScoreFlag().equals(0)){
//                    c.setCourseTips("请先完成："+childCourse.getDayDate()+" "+childCourse.getStartTime()+"-"+childCourse.getEndTime()+","+childCourse.getTeacherName()+"老师 课程的成绩录入。");
//                }
//            }
            //课程提醒
            String str =checkCourseAllTips(c);
            if(existTips.containsKey(str)){
                str ="";
            }else {
                existTips.put(str,str);
            }
            c.setCourseTips(str);
            //新学员提醒
            List<NewChildInfoDTO> newChildInfoDTOS = this.childCourseMapper.listNewChild(c.getId(),c.getDayDate()+" "+c.getStartTime(),c.getClassId());
            if(!CollectionUtils.isEmpty(newChildInfoDTOS)){
                String tempStr="";
                for(NewChildInfoDTO n:newChildInfoDTOS){
                    if(n.getTotalCount()!=null && n.getTotalCount()<2){
                        tempStr+=n.getChildName()+" 是新学员，请老师关注。<br>";
                        continue;
                    }
                    if(n.getTotalCount()!=null && n.getSameClassCount()<=0){
                        tempStr+=n.getChildName()+" 第一次在本班上课，请老师关注。<br>";
                        continue;
                    }
                }
                c.setNewChildTips(tempStr);
            }
            //年龄跨度大提醒
            List<ChildAgeDTO> ageList =this.childCourseMapper.listAge(c.getId());
            c.setChildAgeTips("");
            if(!CollectionUtils.isEmpty(ageList)){
                if(ageList.get(0)!=null && ageList.get(ageList.size()-1) !=null && ageList.get(ageList.size()-1).getAge() - ageList.get(0).getAge()>4){
                    c.setChildAgeTips("学员"+ageList.get(0).getChildName()+""+ageList.get(0).getAge()+"岁、"+ageList.get(ageList.size()-1).getChildName()+""+ageList.get(ageList.size()-1).getAge()+"岁班级内学员之间年龄差异较大，请老师关注。");
                }
            }

        }
        return childCourses;
    }

    @Override
    public List<ChildCourse> listReadingComprehension(ChildCourseDTO dto, SysUser sysUser) {
        if (dto.getCenterId() == null) {
            throw new BusinessException("请选择中心。");
        }
        ChildCourseExample example = new ChildCourseExample();
        if (dto.getScheduleTime() == null || dto.getScheduleTime() == "") {
            dto.setScheduleTime(DateUtils.getDate());
        }
        ChildCourseExample.Criteria criteria = example.createCriteria();
        criteria.andDayDateEqualTo(dto.getScheduleTime());
        criteria.andCenterIdEqualTo(dto.getCenterId());
        if (dto != null && dto.getTeacherName() != null && dto.getTeacherName() != "") {
            criteria.andTeacherNameLike(dto.getTeacherName());
        }
        //只有校区老师角色只看他自己课程
        boolean temp =true;
        if(sysUser !=null){
            for(SysRole role:sysUser.getRoles()){
                if(!role.getRoleKey().equals("teacher")){
                    temp=false;
                }
            }
            if(!temp){
                dto.setTeacherId(null);
            }
        }
        List<ChildCourse> childCourses = childCourseMapper.listReadingComprehension(dto.getScheduleTime(), String.valueOf(dto.getCenterId()), dto.getTeacherName(),dto.getTeacherId());
        Map<String,String> existTips=new HashMap<>();
        for (ChildCourse c : childCourses) {
            c.setChildInfoDTOList(this.childCourseMapper.listChildInfo(c.getId()));
            c.setWeekDay(DateUtils.getWeekDay(DateUtils.parseDate(dto.getScheduleTime())));
            //是否显示未上课：（1）当前课程已备课   （2）当前时间≥课程的下课时间。
            if (c.getScoreFlag()!=null&&  !c.getScoreFlag().equals(1) &&c.getPrepareStatus().equals(1) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate())) {
                c.setShowNotClass(1);
            }
            //是否显示取消备课：（1）当前课程已备课 （2）当前时间≥课程的上课课时间。
            if (c.getPrepareStatus().equals(1) && DateUtils.getNowDate().before(DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()))) {
                c.setShowCancelClass(1);
            }
            //1-未上课，2-上课中，3-已上课，4-已过期
            //当前时间≥课程的上课时间
            if (( DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()).after(DateUtils.getNowDate()))) {
                c.setCourseStatus(1);
            }
            //当前时间≥课程的上课时间 AND 当前时间<=课程的下课时间。
            if ( DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()).before(DateUtils.getNowDate())
                    && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).after(DateUtils.getNowDate())) {
                c.setCourseStatus(2);
            }
            //已备课且课程时间已过，显示已上课
            if (c.getPrepareStatus().equals(1) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate())) {
                c.setCourseStatus(3);
            }
            //未备课且课程时间已经开始，显示已过期
            if (c.getPrepareStatus().equals(2) ||(c.getPrepareStatus().equals(0) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate()))) {
                c.setCourseStatus(4);
            }
            for(ChildInfoDTO cif:c.getChildInfoDTOList()){
                cif.setAge(AgeUtils.buildAge(cif.getBirthYear(),cif.getBirthMonth(),cif.getBirthDay()));
                cif.setGrade(AgeUtils.getGrade(StringUtils.getInt(cif.getGrade())));
            }
            //课程提醒
            //预关联教案  未开始的只有一节课预关联教案
            if(c.getClassPlanId()==null){
                //判断是否符合预关联条件：1、该节课程未过期，且是未过期课程的第一节课 2、上节课已填写成绩
                //2、上节课已填写成绩 判断
                ChildCourse lastSchedule = this.childCourseMapper.getNoScoreSchedule(c.getClassId());
                if(lastSchedule!=null){
                    c.setCourseTips(lastSchedule.getDayDate() + " " + lastSchedule.getStartTime() + "-" + lastSchedule.getEndTime() +lastSchedule.getTeacherName()+"老师  " +  "课程记录未提交，请提交后再备课。<br>");
                    continue;
                }
                // 1、该节课程未过期，且是未过期课程的第一节课 判断
                ChildCourse fistCourseId =this.childCourseMapper.getFistCourseId(c.getClassId(),Constants.COURSE_READING);
                if(fistCourseId !=null&& c.getId().equals(fistCourseId.getId())){
                    //获取当前班级上一节课已完成教案序号
                    int completeClassTimes = this.childCourseMapper.getCompletePlan(c.getClassId());
                    ReadingComprehensionPlan readingComprehensionPlan = this.readingComprehensionPlanMapper.getNextPlan(Integer.valueOf(c.getAgeGrade()),(completeClassTimes%48)+1,Constants.COURSE_READING);
                    if(readingComprehensionPlan!=null){
                        c.setFileName(readingComprehensionPlan.getFileName());
                        c.setFileUrl(readingComprehensionPlan.getFileUrl());
                        c.setClassPlanId(readingComprehensionPlan.getId());
                        completeClassTimes+=1;
                        c.setClassTimes(completeClassTimes);
                    }

                }else if(fistCourseId !=null){
                    c.setLastClassTips("请先完成:"+fistCourseId.getDayDate() + " " + fistCourseId.getStartTime() + "-" + fistCourseId.getEndTime() +","+fistCourseId.getTeacherName()+"老师  " +  "课程备课。<br>");
                }
            }
        }
        return childCourses;
    }

    @Override
    public List<ChildCourse> listLearning(ChildCourseDTO dto, SysUser sysUser) {
        if (dto.getCenterId() == null) {
            throw new BusinessException("请选择中心。");
        }
        ChildCourseExample example = new ChildCourseExample();
        if (dto.getScheduleTime() == null || dto.getScheduleTime() == "") {
            dto.setScheduleTime(DateUtils.getDate());
        }
        ChildCourseExample.Criteria criteria = example.createCriteria();
        criteria.andDayDateEqualTo(dto.getScheduleTime());
        criteria.andCenterIdEqualTo(dto.getCenterId());
        if (dto != null && dto.getTeacherName() != null && dto.getTeacherName() != "") {
            criteria.andTeacherNameLike(dto.getTeacherName());
        }
        //只有校区老师角色只看他自己课程
        boolean temp =true;
        if(sysUser !=null){
            for(SysRole role:sysUser.getRoles()){
                if(!role.getRoleKey().equals("teacher")){
                    temp=false;
                }
            }
            if(!temp){
                dto.setTeacherId(null);
            }
        }
        List<ChildCourse> childCourses = childCourseMapper.listLearning(dto.getScheduleTime(), String.valueOf(dto.getCenterId()), dto.getTeacherName(),dto.getTeacherId());
        Map<String,String> existTips=new HashMap<>();
        for (ChildCourse c : childCourses) {
            c.setChildInfoDTOList(this.childCourseMapper.listChildInfo(c.getId()));
            c.setWeekDay(DateUtils.getWeekDay(DateUtils.parseDate(dto.getScheduleTime())));
            //是否显示未上课：（1）当前课程已备课   （2）当前时间≥课程的下课时间。
            if (c.getScoreFlag()!=null&&  !c.getScoreFlag().equals(1) &&c.getPrepareStatus().equals(1) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate())) {
                c.setShowNotClass(1);
            }
            //是否显示取消备课：（1）当前课程已备课 （2）当前时间≥课程的上课课时间。
            if (c.getPrepareStatus().equals(1) && DateUtils.getNowDate().before(DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()))) {
                c.setShowCancelClass(1);
            }
            //1-未上课，2-上课中，3-已上课，4-已过期
            //当前时间≥课程的上课时间
            if (( DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()).after(DateUtils.getNowDate()))) {
                c.setCourseStatus(1);
            }
            //当前时间≥课程的上课时间 AND 当前时间<=课程的下课时间。
            if ( DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()).before(DateUtils.getNowDate())
                    && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).after(DateUtils.getNowDate())) {
                c.setCourseStatus(2);
            }
            //已备课且课程时间已过，显示已上课
            if (c.getPrepareStatus().equals(1) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate())) {
                c.setCourseStatus(3);
            }
            //未备课且课程时间已经开始，显示已过期
            if (c.getPrepareStatus().equals(2) ||(c.getPrepareStatus().equals(0) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate()))) {
                c.setCourseStatus(4);
            }
            for(ChildInfoDTO cif:c.getChildInfoDTOList()){
                cif.setAge(AgeUtils.buildAge(cif.getBirthYear(),cif.getBirthMonth(),cif.getBirthDay()));
                cif.setGrade(AgeUtils.getGrade(StringUtils.getInt(cif.getGrade())));
            }
            //课程提醒
            //预关联教案  未开始的只有一节课预关联教案
            if(c.getClassPlanId()==null){
                //判断是否符合预关联条件：1、该节课程未过期，且是未过期课程的第一节课 2、上节课已填写成绩
                //2、上节课已填写成绩 判断
                ChildCourse lastSchedule = this.childCourseMapper.getNoScoreSchedule(c.getClassId());
                if(lastSchedule!=null){
                    c.setCourseTips(lastSchedule.getDayDate() + " " + lastSchedule.getStartTime() + "-" + lastSchedule.getEndTime() +lastSchedule.getTeacherName()+"老师  " +  "课程记录未提交，请提交后再备课。<br>");
                    continue;
                }
                // 1、该节课程未过期，且是未过期课程的第一节课 判断
                ChildCourse fistCourseId =this.childCourseMapper.getFistCourseId(c.getClassId(),Constants.COURSE_LEARNING);
                if(fistCourseId !=null&& c.getId().equals(fistCourseId.getId())){
                    //获取当前班级上一节课已完成教案序号
                    int completeClassTimes = this.childCourseMapper.getCompletePlan(c.getClassId());
                    ReadingComprehensionPlan readingComprehensionPlan = this.readingComprehensionPlanMapper.getNextPlan(Integer.valueOf(c.getAgeGrade()),(completeClassTimes%24)+1,Constants.COURSE_LEARNING);
                    if(readingComprehensionPlan!=null){
                        c.setFileName(readingComprehensionPlan.getFileName());
                        c.setFileUrl(readingComprehensionPlan.getFileUrl());
                        c.setClassPlanId(readingComprehensionPlan.getId());
                        completeClassTimes+=1;
                        c.setClassTimes(completeClassTimes);
                    }

                }else if(fistCourseId !=null){
                    c.setLastClassTips("请先完成:"+fistCourseId.getDayDate() + " " + fistCourseId.getStartTime() + "-" + fistCourseId.getEndTime() +","+fistCourseId.getTeacherName()+"老师  " +  "课程备课。<br>");
                }
            }
        }
        return childCourses;
    }

    @Override
    public List<ChildCourse> listSensory(ChildCourseDTO dto, SysUser sysUser) {
        if (dto.getCenterId() == null) {
            throw new BusinessException("请选择中心。");
        }
        ChildCourseExample example = new ChildCourseExample();
        if (dto.getScheduleTime() == null || dto.getScheduleTime() == "") {
            dto.setScheduleTime(DateUtils.getDate());
        }
        ChildCourseExample.Criteria criteria = example.createCriteria();
        criteria.andDayDateEqualTo(dto.getScheduleTime());
        criteria.andCenterIdEqualTo(dto.getCenterId());
        if (dto != null && dto.getTeacherName() != null && dto.getTeacherName() != "") {
            criteria.andTeacherNameLike(dto.getTeacherName());
        }
        //只有校区老师角色只看他自己课程
        boolean temp =true;
        if(sysUser !=null){
            for(SysRole role:sysUser.getRoles()){
                if(!role.getRoleKey().equals("teacher")){
                    temp=false;
                }
            }
            if(!temp){
                dto.setTeacherId(null);
            }
        }
        List<ChildCourse> childCourses = childCourseMapper.listSensory(dto.getScheduleTime(), String.valueOf(dto.getCenterId()), dto.getTeacherName(),dto.getTeacherId());
        Map<String,String> existTips=new HashMap<>();
        for (ChildCourse c : childCourses) {
            c.setChildInfoDTOList(this.childCourseMapper.listChildInfo(c.getId()));
            c.setWeekDay(DateUtils.getWeekDay(DateUtils.parseDate(dto.getScheduleTime())));
            //是否显示未上课：（1）当前课程已备课   （2）当前时间≥课程的下课时间。
            if (c.getScoreFlag()!=null&&  !c.getScoreFlag().equals(1) &&c.getPrepareStatus().equals(1) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate())) {
                c.setShowNotClass(1);
            }
            //是否显示取消备课：（1）当前课程已备课 （2）当前时间≥课程的上课课时间。
            if (c.getPrepareStatus().equals(1) && DateUtils.getNowDate().before(DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()))) {
                c.setShowCancelClass(1);
            }
            //1-未上课，2-上课中，3-已上课，4-已过期
            //当前时间≥课程的上课时间
            if (( DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()).after(DateUtils.getNowDate()))) {
                c.setCourseStatus(1);
            }
            //当前时间≥课程的上课时间 AND 当前时间<=课程的下课时间。
            if ( DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()).before(DateUtils.getNowDate())
                    && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).after(DateUtils.getNowDate())) {
                c.setCourseStatus(2);
            }
            //已备课且课程时间已过，显示已上课
            if (c.getPrepareStatus().equals(1) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate())) {
                c.setCourseStatus(3);
            }
            //未备课且课程时间已经开始，显示已过期
            if (c.getPrepareStatus().equals(2) ||(c.getPrepareStatus().equals(0) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate()))) {
                c.setCourseStatus(4);
            }
            for(ChildInfoDTO cif:c.getChildInfoDTOList()){
                cif.setAge(AgeUtils.buildAge(cif.getBirthYear(),cif.getBirthMonth(),cif.getBirthDay()));
                cif.setGrade(AgeUtils.getGrade(StringUtils.getInt(cif.getGrade())));
            }
            //课程提醒
            //预关联教案  未开始的只有一节课预关联教案
            if(c.getClassPlanId()==null){
                //判断是否符合预关联条件：1、该节课程未过期，且是未过期课程的第一节课 2、上节课已填写成绩
                //2、上节课已填写成绩 判断
                ChildCourse lastSchedule = this.childCourseMapper.getNoScoreSchedule(c.getClassId());
                if(lastSchedule!=null){
                    c.setCourseTips(lastSchedule.getDayDate() + " " + lastSchedule.getStartTime() + "-" + lastSchedule.getEndTime() +lastSchedule.getTeacherName()+"老师  " +  "课程记录未提交，请提交后再备课。<br>");
                    continue;
                }
                // 1、该节课程未过期，且是未过期课程的第一节课 判断
                ChildCourse fistCourseId =this.childCourseMapper.getFistCourseId(c.getClassId(),Constants.COURSE_SENSORY);
                if(fistCourseId !=null&& c.getId().equals(fistCourseId.getId())){
                    //获取当前班级上一节课已完成教案序号
                    int completeClassTimes = this.childCourseMapper.getCompletePlan(c.getClassId());
                    ReadingComprehensionPlan readingComprehensionPlan = this.readingComprehensionPlanMapper.getNextPlan(Integer.  valueOf(c.getAgeGrade()),(completeClassTimes%24)+1,Constants.COURSE_SENSORY);
                    if(readingComprehensionPlan!=null){
                        c.setFileName(readingComprehensionPlan.getFileName());
                        c.setFileUrl(readingComprehensionPlan.getFileUrl());
                        c.setClassPlanId(readingComprehensionPlan.getId());
                        completeClassTimes+=1;
                        c.setClassTimes(completeClassTimes);
                    }

                }else if(fistCourseId !=null){
                    c.setLastClassTips("请先完成:"+fistCourseId.getDayDate() + " " + fistCourseId.getStartTime() + "-" + fistCourseId.getEndTime() +","+fistCourseId.getTeacherName()+"老师  " +  "课程备课。<br>");
                }
            }
        }
        return childCourses;
    }

    @Override
    public List<ChildCourse> listThinking(ChildCourseDTO dto, SysUser sysUser) {
        if (dto.getCenterId() == null) {
            throw new BusinessException("请选择中心。");
        }
        ChildCourseExample example = new ChildCourseExample();
        if (dto.getScheduleTime() == null || dto.getScheduleTime() == "") {
            dto.setScheduleTime(DateUtils.getDate());
        }
        ChildCourseExample.Criteria criteria = example.createCriteria();
        criteria.andDayDateEqualTo(dto.getScheduleTime());
        criteria.andCenterIdEqualTo(dto.getCenterId());
        if (dto != null && dto.getTeacherName() != null && dto.getTeacherName() != "") {
            criteria.andTeacherNameLike(dto.getTeacherName());
        }
        //只有校区老师角色只看他自己课程
        boolean temp =true;
        if(sysUser !=null){
            for(SysRole role:sysUser.getRoles()){
                if(!role.getRoleKey().equals("teacher")){
                    temp=false;
                }
            }
            if(!temp){
                dto.setTeacherId(null);
            }
        }
        List<ChildCourse> childCourses = childCourseMapper.listThinking(dto.getScheduleTime(), String.valueOf(dto.getCenterId()), dto.getTeacherName(),dto.getTeacherId());
        Map<String,String> existTips=new HashMap<>();
        for (ChildCourse c : childCourses) {
            c.setChildInfoDTOList(this.childCourseMapper.listChildInfo(c.getId()));
            c.setWeekDay(DateUtils.getWeekDay(DateUtils.parseDate(dto.getScheduleTime())));
            //是否显示未上课：（1）当前课程已备课   （2）当前时间≥课程的下课时间。
            if (c.getScoreFlag()!=null&&  !c.getScoreFlag().equals(1) &&c.getPrepareStatus().equals(1) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate())) {
                c.setShowNotClass(1);
            }
            //是否显示取消备课：（1）当前课程已备课 （2）当前时间≥课程的上课课时间。
            if (c.getPrepareStatus().equals(1) && DateUtils.getNowDate().before(DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()))) {
                c.setShowCancelClass(1);
            }
            //1-未上课，2-上课中，3-已上课，4-已过期
            //当前时间≥课程的上课时间
            if (( DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()).after(DateUtils.getNowDate()))) {
                c.setCourseStatus(1);
            }
            //当前时间≥课程的上课时间 AND 当前时间<=课程的下课时间。
            if ( DateUtils.parseDate(c.getDayDate() + " " + c.getStartTime()).before(DateUtils.getNowDate())
                    && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).after(DateUtils.getNowDate())) {
                c.setCourseStatus(2);
            }
            //已备课且课程时间已过，显示已上课
            if (c.getPrepareStatus().equals(1) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate())) {
                c.setCourseStatus(3);
            }
            //未备课且课程时间已经开始，显示已过期
            if (c.getPrepareStatus().equals(2) ||(c.getPrepareStatus().equals(0) && DateUtils.parseDate(c.getDayDate() + " " + c.getEndTime()).before(DateUtils.getNowDate()))) {
                c.setCourseStatus(4);
            }
            for(ChildInfoDTO cif:c.getChildInfoDTOList()){
                cif.setAge(AgeUtils.buildAge(cif.getBirthYear(),cif.getBirthMonth(),cif.getBirthDay()));
                cif.setGrade(AgeUtils.getGrade(StringUtils.getInt(cif.getGrade())));
            }
            //预关联教案  未开始的只有一节课预关联教案
            if(c.getClassPlanId()==null){
                //判断是否符合预关联条件：1、该节课程未过期，且是未过期课程的第一节课 2、上节课已填写成绩
                //2、上节课已填写成绩 判断
                ChildCourse lastSchedule = this.childCourseMapper.getNoScoreSchedule(c.getClassId());
                if(lastSchedule!=null){
                    c.setCourseTips(lastSchedule.getDayDate() + " " + lastSchedule.getStartTime() + "-" + lastSchedule.getEndTime() +lastSchedule.getTeacherName()+"老师  " +  "课程记录未提交，请提交后再备课。<br>");
                    continue;
                }
                // 1、该节课程未过期，且是未过期课程的第一节课 判断
                ChildCourse fistCourseId =this.childCourseMapper.getFistCourseId(c.getClassId(),Constants.COURSE_THINKING);
                if(fistCourseId !=null&& c.getId().equals(fistCourseId.getId())){
                    //获取当前班级上一节课已完成教案序号
                    int completeClassTimes = this.childCourseMapper.getCompletePlan(c.getClassId());
                    ReadingComprehensionPlan readingComprehensionPlan = this.readingComprehensionPlanMapper.getNextPlan(Integer.valueOf(c.getAgeGrade()),(completeClassTimes%48)+1, Constants.COURSE_THINKING);
                    if(readingComprehensionPlan!=null){
                        c.setFileName(readingComprehensionPlan.getFileName());
                        c.setFileUrl(readingComprehensionPlan.getFileUrl());
                        c.setClassPlanId(readingComprehensionPlan.getId());
                        completeClassTimes+=1;
                        c.setClassTimes(completeClassTimes);
                    }

                }else if(fistCourseId !=null){
                    c.setLastClassTips("请先完成:"+fistCourseId.getDayDate() + " " + fistCourseId.getStartTime() + "-" + fistCourseId.getEndTime() +","+fistCourseId.getTeacherName()+"老师  " +  "课程备课。<br>");
                }

            }
        }
        return childCourses;
    }

    @Override
    public List<ChildCourse> listSocialize(ChildCourseDTO dto, SysUser sysUser) {
        if (dto.getCenterId() == null) {
            throw new BusinessException("请选择中心。");
        }
        ChildCourseExample example = new ChildCourseExample();
        if (dto.getScheduleTime() == null || dto.getScheduleTime() == "") {
            dto.setScheduleTime(DateUtils.getDate());
        }
        ChildCourseExample.Criteria criteria = example.createCriteria();
        criteria.andDayDateEqualTo(dto.getScheduleTime());
        criteria.andCenterIdEqualTo(dto.getCenterId());
        if (dto != null && dto.getTeacherName() != null && dto.getTeacherName() != "") {
            criteria.andTeacherNameLike(dto.getTeacherName());
        }
        //只有校区老师角色只看他自己课程
        boolean temp =true;
        if(sysUser !=null){
            for(SysRole role:sysUser.getRoles()){
                if(!role.getRoleKey().equals("teacher")){
                    temp=false;
                }
            }
            if(!temp){
                dto.setTeacherId(null);
            }
        }
        List<ChildCourse> childCourses = childCourseMapper.listSocialize(dto.getScheduleTime(), String.valueOf(dto.getCenterId()), dto.getTeacherName(),dto.getTeacherId());

        for (ChildCourse c : childCourses) {
            c.setChildInfoDTOList(this.childCourseMapper.listChildInfo(c.getId()));
            c.setWeekDay(DateUtils.getWeekDay(DateUtils.parseDate(dto.getScheduleTime())));


            for(ChildInfoDTO cif:c.getChildInfoDTOList()){
                cif.setAge(AgeUtils.buildAge(cif.getBirthYear(),cif.getBirthMonth(),cif.getBirthDay()));
                cif.setGrade(AgeUtils.getGrade(StringUtils.getInt(cif.getGrade())));
            }
            //关联教案：本月未确认时，查询上月顺延计划，已确认时按本月计划
            //定义classTimes为当前课程日期是本年第几月
            if(c.getClassPlanId()==null){
                //本月是否已有确认计划，有的话同步更新
                ReadingComprehensionPlan classPlan = childCourseMapper.getClassPlanByClassTimes(c.getClassId(),c.getClassTimes());
                if(classPlan!=null){
                    childCourseMapper.updateClassPlanIdById(c.getId(),classPlan.getId());
                    c.setFileUrl(classPlan.getFileUrl());
                    c.setFileName(classPlan.getFileName());
                    c.setPrepareStatus(1);
                }
                //月底倒数5天，预关联下月计划
                LocalDate current = LocalDate.now();
                if( (ChronoUnit.DAYS.between(LocalDate.now(),current.withDayOfMonth(current.lengthOfMonth()))>=0 &&
                        ChronoUnit.DAYS.between(LocalDate.now(),current.withDayOfMonth(current.lengthOfMonth()))<=5)
                        ||(LocalDate.now().getMonth() == LocalDate.parse(c.getDayDate()).getMonth())){

                    //获取已训练计划序号
                    Integer sort = childCourseMapper.getFusionScheduleCompletePlan(c.getClassId());
                    ReadingComprehensionPlan comprehensionPlan = readingComprehensionPlanMapper.getFusionNextPlan(sort==null?1:sort+1,c.getCourseId());
                    if(comprehensionPlan!=null){
                        c.setClassPlanId(comprehensionPlan.getId());
                        c.setFileUrl(comprehensionPlan.getFileUrl());
                        c.setFileName(comprehensionPlan.getFileName());
                    }
                }


            }
        }
        return childCourses;
    }



    @Override
    public List<ChildCourse> listEnrol(ChildCourseDTO dto, SysUser sysUser) {
        if (dto.getCenterId() == null) {
            throw new BusinessException("请选择中心。");
        }
        ChildCourseExample example = new ChildCourseExample();
        if (dto.getScheduleTime() == null || dto.getScheduleTime() == "") {
            dto.setScheduleTime(DateUtils.getDate());
        }
        ChildCourseExample.Criteria criteria = example.createCriteria();
        criteria.andDayDateEqualTo(dto.getScheduleTime());
        criteria.andCenterIdEqualTo(dto.getCenterId());
        if (dto != null && dto.getTeacherName() != null && dto.getTeacherName() != "") {
            criteria.andTeacherNameLike(dto.getTeacherName());
        }
        //只有校区老师角色只看他自己课程
        boolean temp =true;
        if(sysUser !=null){
            for(SysRole role:sysUser.getRoles()){
                if(!role.getRoleKey().equals("teacher")){
                    temp=false;
                }
            }
            if(!temp){
                dto.setTeacherId(null);
            }
        }
        List<ChildCourse> childCourses = childCourseMapper.listEnrol(dto.getScheduleTime(), String.valueOf(dto.getCenterId()), dto.getTeacherName(),dto.getTeacherId());

        for (ChildCourse c : childCourses) {
            c.setChildInfoDTOList(this.childCourseMapper.listChildInfo(c.getId()));
            c.setWeekDay(DateUtils.getWeekDay(DateUtils.parseDate(dto.getScheduleTime())));

            for(ChildInfoDTO cif:c.getChildInfoDTOList()){
                cif.setAge(AgeUtils.buildAge(cif.getBirthYear(),cif.getBirthMonth(),cif.getBirthDay()));
                cif.setGrade(AgeUtils.getGrade(StringUtils.getInt(cif.getGrade())));
            }
            //关联教案：本周未确认时，查询上周顺延计划，已确认时按本周计划
            //定义classTimes为当前课程日期是本年第几周
            if(c.getClassPlanId()==null){
                //本周是否已有确认计划，有的话同步更新
               ReadingComprehensionPlan classPlan = childCourseMapper.getClassPlanByClassTimes(c.getClassId(),c.getClassTimes());
               if(classPlan!=null){
                   childCourseMapper.updateClassPlanIdById(c.getId(),classPlan.getId());
                   c.setFileUrl(classPlan.getFileUrl());
                   c.setFileName(classPlan.getFileName());
                   c.setPrepareStatus(1);
               }
               //周天或当周，预关联下月计划
                if((DayOfWeek.SUNDAY.equals(LocalDate.now().getDayOfWeek()) &&
                        ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.parse(c.getDayDate()))<9)
                        ||(LocalDate.now().get(IsoFields.WEEK_OF_WEEK_BASED_YEAR) == LocalDate.parse(c.getDayDate()).get(IsoFields.WEEK_OF_WEEK_BASED_YEAR))){
                //本周未确认计划时，按照 “上周最后一天及当周，才可以确认本周的计划”的需求 预关联计划
                //获取已训练计划序号
                Integer sort = childCourseMapper.getFusionScheduleCompletePlan(c.getClassId());
                ReadingComprehensionPlan comprehensionPlan = readingComprehensionPlanMapper.getFusionNextPlan(sort==null?1:sort+1,c.getCourseId());
                if(comprehensionPlan!=null){
                    c.setClassPlanId(comprehensionPlan.getId());
                    c.setFileUrl(comprehensionPlan.getFileUrl());
                    c.setFileName(comprehensionPlan.getFileName());
                }
                }
            }
        }
        return childCourses;
    }


    @Override
    public void initProject(Long childCourseId,String loginUserName) {
        ChildCourse childCourse = this.childCourseMapper.selectById(childCourseId);
        //常规版
        if ( childCourse.getClassType().equals(1)) {
            initClassProject(childCourseId, loginUserName);
        }
        //集训班
        if ( childCourse.getClassType().equals(2)) {
            initThemeProject(childCourse, loginUserName);
        }
    }

    @Override
    public List<CourseChildProject> childList(Long childCourseId, String loginUserName) {
//        List<CourseChildProject> list = this.courseChildProjectMapper.findListByCourse(childCourseId);
//        if (CollectionUtils.isEmpty(list)) {
//            //初始化学生能力配置
//            initClassProject(childCourseId, loginUserName);
//            list = this.courseChildProjectMapper.findListByCourse(childCourseId);
//        } else {
//            ChildCourse childCourse = this.childCourseMapper.selectById(childCourseId);
//            for (CourseChildProject c : list) {
                //classType:班级类型：1常规班，2集训班
//                if ( childCourse.getClassType().equals(1)) {
//                    initClassProject(childCourseId, loginUserName);
////                    break;
//                }
//                if ( childCourse.getClassType().equals(2)) {
//                    initThemeProject(childCourse, loginUserName);
////                    break;
//                }
//            }

        List<CourseChildProject> list = this.courseChildProjectMapper.findListByCourse(childCourseId);
//        }
        List<Integration> integrationList = this.integrationService.getSelectList();
        for (CourseChildProject c : list) {
            c.setAge(AgeUtils.buildAge(c.getBirthYear(), c.getBirthMonth(), c.getBirthDay()));
            int age = AgeUtils.computationsAge(c.getBirthYear(), c.getBirthMonth());
            c.setIntAge(age);
            List<String> configList = this.childProjectConfigMapper.findProjectCodes(c.getChildId());
            //获取学员个项目训练次数
            List<ChildProjectConfig> configList1 = this.childProjectConfigMapper.listAllCompleteTimes(c.getChildId());
            Map<String, Integer> completeTimesMap = new HashMap<>();
            List<String> showDifficultyList =new ArrayList<>();
            for (ChildProjectConfig config : configList1) {
                completeTimesMap.put(config.getProjectCode(), config.getCompleteTimes());
            }

//            if (StringUtils.isNotEmpty(c.getLinkOne())) {
//                c.setTrainAmountOneList(this.integrationTrainAmountMapper.listByChild(c.getChildId(), c.getLinkOne()));
//            }
            if (StringUtils.isNotEmpty(c.getInitOne())) {
                c.setLinkOneOptions(this.dealOptions(integrationList, c.getInitOne(), c.getLinkOne(), configList, completeTimesMap));
                showDifficultyList =this.checkShowDifficulty(c.getChildId(),age,c.getInitOne(),"1",showDifficultyList);
            }
//            if (StringUtils.isNotEmpty(c.getLinkTwo())) {
//                c.setTrainAmountTwoList(this.integrationTrainAmountMapper.listByChild(c.getChildId(), c.getLinkTwo()));
//            }
            if (StringUtils.isNotEmpty(c.getInitTwo())) {
                c.setLinkTwoOptions(this.dealOptions(integrationList, c.getInitTwo(), c.getLinkTwo(), configList, completeTimesMap));
                showDifficultyList =this.checkShowDifficulty(c.getChildId(),age,c.getInitTwo(),"2",showDifficultyList);
            }
//            if (StringUtils.isNotEmpty(c.getLinkThree())) {
//                c.setTrainAmountThreeList(this.integrationTrainAmountMapper.listByChild(c.getChildId(), c.getLinkThree()));
//            }
            if (StringUtils.isNotEmpty(c.getInitThree())) {
                c.setLinkThreeOptions(this.dealOptions(integrationList, c.getInitThree(), c.getLinkThree(), configList, completeTimesMap));
                showDifficultyList =this.checkShowDifficulty(c.getChildId(),age,c.getInitThree(),"3",showDifficultyList);
            }
//            if (StringUtils.isNotEmpty(c.getLinkFour())) {
//                c.setTrainAmountFourList(this.integrationTrainAmountMapper.listByChild(c.getChildId(), c.getLinkFour()));
//            }
            if (StringUtils.isNotEmpty(c.getInitFour())) {
                c.setLinkFourOptions(this.dealOptions(integrationList, c.getInitFour(), c.getLinkFour(), configList, completeTimesMap));
                showDifficultyList =this.checkShowDifficulty(c.getChildId(),age,c.getInitFour(),"4",showDifficultyList);
            }
//            if (StringUtils.isNotEmpty(c.getLinkFive())) {
//                c.setTrainAmountFiveList(this.integrationTrainAmountMapper.listByChild(c.getChildId(), c.getLinkFive()));
//            }
            if (StringUtils.isNotEmpty(c.getInitFive())) {
                c.setLinkFiveOptions(this.dealOptions(integrationList, c.getInitFive(), c.getLinkFive(), configList, completeTimesMap));
                showDifficultyList =this.checkShowDifficulty(c.getChildId(),age,c.getInitFive(),"5",showDifficultyList);
            }
//            if (StringUtils.isNotEmpty(c.getLinkSix())) {
//                c.setTrainAmountSixList(this.integrationTrainAmountMapper.listByChild(c.getChildId(), c.getLinkSix()));
//            }
            if (StringUtils.isNotEmpty(c.getInitSix())) {
                c.setLinkSixOptions(this.dealOptions(integrationList, c.getInitSix(), c.getLinkSix(), configList, completeTimesMap));
                showDifficultyList =this.checkShowDifficulty(c.getChildId(),age,c.getInitSix(),"6",showDifficultyList);
            }
//            if (StringUtils.isNotEmpty(c.getLinkSeven())) {
//                c.setTrainAmountSevenList(this.integrationTrainAmountMapper.listByChild(c.getChildId(), c.getLinkSeven()));
//            }
            if (StringUtils.isNotEmpty(c.getInitSeven())) {
                c.setLinkSevenOptions(this.dealOptions(integrationList, c.getInitSeven(), c.getLinkSeven(), configList, completeTimesMap));
                showDifficultyList =this.checkShowDifficulty(c.getChildId(),age,c.getInitSeven(),"7",showDifficultyList);
            }
//            if (StringUtils.isNotEmpty(c.getLinkEight())) {
//                c.setTrainAmountEightList(this.integrationTrainAmountMapper.listByChild(c.getChildId(), c.getLinkEight()));
//            }
            if (StringUtils.isNotEmpty(c.getInitEight())) {
                c.setLinkEightOptions(this.dealOptions(integrationList, c.getInitEight(), c.getLinkEight(), configList, completeTimesMap));
                showDifficultyList =this.checkShowDifficulty(c.getChildId(),age,c.getInitEight(),"8",showDifficultyList);
            }
//            if (StringUtils.isNotEmpty(c.getLinkNine())) {
//                c.setTrainAmountNineList(this.integrationTrainAmountMapper.listByChild(c.getChildId(), c.getLinkNine()));
//            }
            if (StringUtils.isNotEmpty(c.getInitNine())) {
                c.setLinkNineOptions(this.dealOptions(integrationList, c.getInitNine(), c.getLinkNine(), configList, completeTimesMap));
                showDifficultyList =this.checkShowDifficulty(c.getChildId(),age,c.getInitNine(),"9",showDifficultyList);
            }
            c.setLockProjects("");
            c.setShowDifficultyList(showDifficultyList);
        }
        return list;
    }

    /**
     * 判断是否显示困难
     * @return
     */
    private List<String> checkShowDifficulty(Long childId,int age,String initProjectCode,String linkNo,List<String> showDifficultyList){
        String result=null;
        //判断该环节下项目是否符合学生年龄范围
        if(StringUtils.isNotEmpty(initProjectCode)){
            int count = this.integrationMapper.selectProjectCountByAge(StringUtils.split2List(initProjectCode,',').get(0),age);
            if(count <=0){
                showDifficultyList.add(linkNo);
            }
        }
        return showDifficultyList;
    }

    @Override
    public List<ChildInfoDTO> childInfo(Long childCourseId) {
        List<ChildInfoDTO> list = this.courseChildMapper.childInfoList(childCourseId);
        for (ChildInfoDTO c : list) {
            c.setAge(AgeUtils.buildAge(c.getBirthYear(), c.getBirthMonth(), c.getBirthDay()));
        }
        return list;
    }

    private List<IntegrationDTO> dealOptions(List<Integration> integrationList, String initProjectCode,
                                             String linkProjectCode, List<String> lockProjects, Map<String, Integer> completeTimesMap) {
        List<IntegrationDTO> result = new ArrayList<>();
        List<String> existCode = new ArrayList<>();
        List<String> initProjectCodeList = StringUtils.split2List(initProjectCode, ',');
        for (String code : initProjectCodeList) {
            if (existCode.contains(code)) {
                continue;
            }
            for (Integration i : integrationList) {
                if (i.getLeafType().equals(2) && code.equals(i.getCode())) {
                    IntegrationDTO dto = new IntegrationDTO();
                    dto.setLeafType(2);
                    dto.setProjectCode(i.getCode());
                    dto.setProjectName(i.getName());
                    List<IntegrationDTO> childList = new ArrayList<>();
                    for (Integration i1 : integrationList) {
                        if (i1.getLeafType().equals(4) && code.equals(i1.getParentCode()) && lockProjects.contains(i1.getCode())) {
                            IntegrationDTO dto1 = new IntegrationDTO();
                            dto1.setLeafType(4);
                            dto1.setProjectCode(i1.getCode());
                            dto1.setProjectName(i1.getName() + (completeTimesMap.containsKey(i1.getCode()) ? ("(" + completeTimesMap.get(i1.getCode()) + "次)") : ""));
                            dto1.setHasSelect(i1.getCode().equalsIgnoreCase(linkProjectCode));
                            childList.add(dto1);
                        }
                    }

                    dto.setChildList(childList);
                    result.add(dto);
                    existCode.add(i.getCode());
                    break;
                }
                if (i.getLeafType().equals(4) && i.getCode().indexOf(code) > -1 && lockProjects.indexOf(i.getCode()) > -1) {
                    IntegrationDTO dto = new IntegrationDTO();
                    dto.setLeafType(4);
                    dto.setProjectCode(i.getCode());
                    dto.setProjectName(i.getName() + (completeTimesMap.containsKey(i.getCode()) ? ("(" + completeTimesMap.get(i.getCode()) + "次)") : ""));
                    dto.setHasSelect(i.getCode().equalsIgnoreCase(linkProjectCode));
                    result.add(dto);
                    existCode.add(i.getCode());
                    break;
                }
            }
        }
        return result;
    }


    @Override
    public void initClassProjectOld(Long childCourseId, String loginUserName) {
        //1、获取课程：年龄、年级、班级类型，第几节课、小孩id
        ChildCourseDTO dto = this.childCourseMapper.getCourseInfo(childCourseId);
        if (dto == null || StringUtils.isEmpty(dto.getChildIds())) {
            return;
        }

        //2、是否该班级第一节课，第一节课时判断本年出题顺序并保存 k_class_plan_sort
        String classPlanSortTemp = "";
        if (dto.getCompleteClassTimes().equals(0)
                && dto.getClassPlanSort() == null) {
            classPlanSortTemp = DictUtils.getDictLabel("class_plan_sort", String.valueOf(DateUtils.getYear(new Date()) % 2));
            ClassPlanSort classPlanSort = new ClassPlanSort();
            classPlanSort.setId(IdWorker.getId());
            classPlanSort.setClassPlanSort(classPlanSortTemp);
            dto.setClassPlanSort(classPlanSortTemp);
            classPlanSort.setClassId(dto.getClassId());
            classPlanSort.setCreateTime(DateUtils.getNowDate());
            classPlanSort.setCreateUser(loginUserName);
            this.classPlanSortMapper.insert(classPlanSort);
        }
        dto.setSortList(CollectionUtils.arrayToList(dto.getClassPlanSort().split(",")));
        //3、按照该班级的年计划顺序获取训练计划list
        List<ClassPlan> classPlanList = classPlanMapper.getClassPlan(dto);
        int totalClass = 0;
        Long reqClassPlanId = null;
        int reqClassTimes = 0;
        for (int i = 0; i < classPlanList.size(); i++) {//匹配对应课次的训练计划id 和课次
            if (i == 0) {
                totalClass = classPlanList.get(i).getTotalClassTimes();
                if (dto.getCompleteClassTimes() < totalClass) {
                    reqClassPlanId = Long.valueOf(classPlanList.get(i).getId());
                    reqClassTimes = dto.getCompleteClassTimes() + 1;
                    break;
                }
                continue;
            }

            if (dto.getCompleteClassTimes() < (totalClass + classPlanList.get(i).getTotalClassTimes())) {
                reqClassPlanId = Long.valueOf(classPlanList.get(i).getId());
                reqClassTimes = dto.getCompleteClassTimes() - totalClass + 1;
            } else {
                totalClass += totalClass + classPlanList.get(i).getTotalClassTimes();
            }
        }
        //获取符合训练计划的各环节项目
        List<ClassPlanDetail> classPlanDetailList = this.classPlanDetailMapper.findList(reqClassPlanId, reqClassTimes);
        String[] childIds = dto.getChildIds().split(",");
        for (String s : childIds) {//各学生处理
            Long childId = Long.valueOf(s);
            //4、保存各环节初始化项目
            //4.1判断学生是否初始化能力配置，未初始化的学生调用初始化
            int configCount = this.childProjectConfigMapper.selectCount(childId);
            if (configCount <= 0) {
                initRule.initConfig(childId);
            }
            //获取学生能力配置
            List<ChildProjectConfig> configList = this.childProjectConfigMapper.findList(childId);
            Map<String, Object> configMap = new HashMap<>();
            for (ChildProjectConfig c : configList) {
                configMap.put(c.getProjectCode(), c);
            }
            //4.2结合学生能力初始化当节课项目
            CourseChildProject courseChildProject = new CourseChildProject();
            courseChildProject.setChildCourseId(childCourseId);
            courseChildProject.setChildId(childId);
            courseChildProject.setCreateTime(DateUtils.getNowDate());
            courseChildProject.setCreateUser(loginUserName);
            for (ClassPlanDetail c : classPlanDetailList) {
                dealInitProject(configMap, courseChildProject, c, dto,-1);
            }
            //保存能力配置
            this.courseChildProjectMapper.insert(courseChildProject);
        }
    }

    @Override
    public void initClassProject(Long childCourseId, String loginUserName) {
        //获取该班级之前上到第几节课
        ChildCourseDTO dto = new ChildCourseDTO();
        ChildCourse childCourseComplete = this.childCourseMapper.getCompleteTimes(childCourseId);
        ChildCourse currentCourse = this.childCourseMapper.selectById(childCourseId);
        dto.setAgeGrade(currentCourse.getAgeGrade());
        dto.setClassType(currentCourse.getClassType());
        dto.setClassId(currentCourse.getClassId());
        String classPlanSortTemp = "";
        if (currentCourse.getClassPlanId() == null) {
            return;
        }
        if (childCourseComplete == null) {
            childCourseComplete = new ChildCourse();
            childCourseComplete.setClassTimes(0);
        }



        //获取符合训练计划的各环节项目
        List<ClassPlanDetail> classPlanDetailList = this.classPlanDetailMapper.findList(currentCourse.getClassPlanId(), childCourseComplete.getClassTimes() + 1);

        //判断训练计划是否全部训练完成
        if(CollectionUtils.isEmpty(classPlanDetailList)){
            ClassPlan classPlan =this.classPlanMapper.selectById(currentCourse.getClassPlanId());
            if(classPlan!=null && (childCourseComplete.getClassTimes() + 1)>classPlan.getTotalClassTimes()){
                childCourseComplete.setClassTimes(0);
                classPlanDetailList = this.classPlanDetailMapper.findList(currentCourse.getClassPlanId(), childCourseComplete.getClassTimes() + 1);
            }
        }

        //获取本班学生
        List<Child> childList = this.courseChildMapper.listCourseChild(childCourseId);
        for (Child child : childList) {//各学生处理
            CourseChildProject local = this.courseChildProjectMapper.selectOne(childCourseId, child.getId());
            if (local != null) {
                continue;
            }
            int age = AgeUtils.computationsAge(child.getBirthYear(), child.getBirthMonth());
            //4、保存各环节初始化项目
            //4.1判断学生是否初始化能力配置，未初始化的学生调用初始化
            int configCount = this.childProjectConfigMapper.selectCount(child.getId());
            if (configCount <= 0) {
                initRule.initConfig(child.getId());
            }
            //获取学生能力配置
            List<ChildProjectConfig> configList = this.childProjectConfigMapper.findList(child.getId());
            Map<String, Object> configMap = new HashMap<>();
            for (ChildProjectConfig c : configList) {
                configMap.put(c.getProjectCode(), c);
            }
            //4.2结合学生能力初始化当节课项目
            CourseChildProject courseChildProject = new CourseChildProject();
            courseChildProject.setChildCourseId(childCourseId);
            courseChildProject.setChildId(child.getId());
            courseChildProject.setCreateTime(DateUtils.getNowDate());
            courseChildProject.setCreateUser(loginUserName);
            for (ClassPlanDetail c : classPlanDetailList) {
                dealInitProject(configMap, courseChildProject, c, dto,age);
            }
            //保存本节课初始化项目
            this.courseChildProjectMapper.insert(courseChildProject);
        }
        this.childCourseMapper.updateClassTimes(currentCourse.getId(), childCourseComplete.getClassTimes() + 1);
    }

    @Override
    public void initThemeProject(ChildCourse childCourse,String loginUserName) {
        //获取符合训练计划的各环节项目
        List<ClassPlanDetail> classPlanDetailList = null;
        String redisKey="theme:"+childCourse.getClassId();
        int tempClassTimes = 0;
        String projects=null;
        //判断本班是否初始化项目过；
        if(null==childCourse.getClassTimes()){
//            projects =redisTemplate.opsForValue().get(redisKey);
//            if (!StringUtils.isEmpty(projects)) {
//                JSONObject object = JSONObject.parseObject(projects);
//                List<Integer> classList =(List<Integer>) object.get("classTimes");
//                if(classList.size()>0){
//                    tempClassTimes = classList.get(0);
//                    //判断本班级今天有没有已备课课程
//                    //若集训班每天两节运动力课在按照课表出项目；若每天仅一节课则选择用每天的第一节课，即第1、3、5、7、9节课。
//                    int count= this.childCourseMapper.countPreparedClassId(childCourse.getClassId(),childCourse.getDayDate());
//                    if(count<=0 && tempClassTimes%2==0){
//                        classList.remove(0);
//                    }
//                    tempClassTimes =classList.get(0);
//                    classList.remove(0);
//                    object.put("classTimes",classList);
//                    projects = object.toJSONString();
//                }
//                classPlanDetailList = this.classPlanDetailMapper.findList(Long.valueOf(StringUtils.getString(object.get("classPlanId"))),  tempClassTimes);
//            }
        }else {
            tempClassTimes = childCourse.getClassTimes();
            classPlanDetailList = this.classPlanDetailMapper.findList(childCourse.getClassPlanId(), tempClassTimes);
        }


        //获取本班学生
        List<Child> childList = this.courseChildMapper.listCourseChild(childCourse.getId());
        for (Child child : childList) {//各学生处理
            CourseChildProject local = this.courseChildProjectMapper.selectOne(childCourse.getId(), child.getId());
            if (local != null) {
                continue;
            }
            int age = AgeUtils.computationsAge(child.getBirthYear(), child.getBirthMonth());
            //4.1判断学生是否初始化能力配置，未初始化的学生调用初始化
            int configCount = this.childProjectConfigMapper.selectCount(child.getId());
            if (configCount <= 0) {
                initRule.initConfig(child.getId());
            }
            List<ChildProjectConfig> configList = this.childProjectConfigMapper.findList(child.getId());
            Map<String, Object> configMap = new HashMap<>();
            for (ChildProjectConfig c : configList) {
                configMap.put(c.getProjectCode(), c);
            }
            //4.2结合学生能力初始化当节课项目
            CourseChildProject courseChildProject = new CourseChildProject();
            courseChildProject.setChildCourseId(childCourse.getId());
            courseChildProject.setChildId(child.getId());
            courseChildProject.setCreateTime(DateUtils.getNowDate());
            courseChildProject.setCreateUser(loginUserName);
            for (ClassPlanDetail c : classPlanDetailList) {
                dealInitProject(configMap, courseChildProject, c, null,age);
            }
            //保存本节课初始化项目
            this.courseChildProjectMapper.insert(courseChildProject);
        }
        this.childCourseMapper.updateClassTimes(childCourse.getId(), tempClassTimes);
        if(null == childCourse.getClassTimes()){
//            redisTemplate.opsForValue().set(redisKey,projects);
        }

    }

    private void dealInitProject(Map<String, Object> configMap, CourseChildProject courseChildProject, ClassPlanDetail c, ChildCourseDTO dto,int age) {

        List<String> initProjectList = new ArrayList<>();
        String projectCode = null;
        //自选环节、课表环节,获取小孩能做的项目
        if ((c.getLinkRuleType().equals(1) || c.getLinkRuleType().equals(3)) && StringUtils.isNotEmpty(c.getProjectCode())) {
            List<Integration> integrationList = this.integrationService.findListByCode(CollectionUtils.arrayToList(c.getProjectCode().split(",")));
            for (Integration i : integrationList) {
                if (i.getLeafType() != 4) {
                    initProjectList.add(i.getCode());
                }
                if (i.getLeafType() == 4 ) {
                    initProjectList.add(i.getCode());
                }

            }
        }
        //训练包环节,本节课该出的项目
        if (c.getLinkRuleType().equals(2)) {
            String key = dto.getClassId() + ":" + c.getLinkNo() + "_project";
            String projects = redisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(projects)) {
                JSONObject object = JSONObject.parseObject(projects);
                List<String> projectList = StringUtils.split2List(StringUtils.getString(object.get("project")), ',');
                int trainPackageTimes = Integer.valueOf(StringUtils.getString(object.get("count")));
                if (projectList.size() > 0) {
                    initProjectList.add(projectList.get(0));
                }
            }
        }
        switch (c.getLinkNo()) {
            case 1:
                courseChildProject.setInitOne(StringUtils.list2String(initProjectList, ","));
                break;
            case 2:
                courseChildProject.setInitTwo(StringUtils.list2String(initProjectList, ","));
                checkProjectAge(courseChildProject.getChildId(),age,initProjectList);
                break;
            case 3:
                courseChildProject.setInitThree(StringUtils.list2String(initProjectList, ","));
                checkProjectAge(courseChildProject.getChildId(),age,initProjectList);
                break;
            case 4:
                courseChildProject.setInitFour(StringUtils.list2String(initProjectList, ","));
                checkProjectAge(courseChildProject.getChildId(),age,initProjectList);
                break;
            case 5:
                courseChildProject.setInitFive(StringUtils.list2String(initProjectList, ","));
                checkProjectAge(courseChildProject.getChildId(),age,initProjectList);
                break;
            case 6:
                courseChildProject.setInitSix(StringUtils.list2String(initProjectList, ","));
                checkProjectAge(courseChildProject.getChildId(),age,initProjectList);
                break;
            case 7:
                courseChildProject.setInitSeven(StringUtils.list2String(initProjectList, ","));
                checkProjectAge(courseChildProject.getChildId(),age,initProjectList);
                break;
            case 8:
                courseChildProject.setInitEight(StringUtils.list2String(initProjectList, ","));
                break;
            case 9:
                courseChildProject.setInitNine(StringUtils.list2String(initProjectList, ","));
                break;
        }

    }

    /**
     * 判断该环节下的项目，学员是否符合年龄范围
     */
    @Async
    public void checkProjectAge(Long childId,int age,List<String> initProjectList){
        List<Integration> needUnlockProjectList =new ArrayList<>();
        if(!CollectionUtils.isEmpty(initProjectList)){
            //判断学员是否有可以做的项目
            for(String s:initProjectList){
                int count = this.childProjectConfigMapper.selectCountByProjectCode(childId,s);
                if(count<=0){
                    List<Integration> integrationList =this.integrationMapper.findListLikeCode(s,age);
                    if(!CollectionUtils.isEmpty(integrationList)){
                        int temp= integrationList.get(0).getStartAge()-age;
                        for(Integration i:integrationList){
                            if(i.getStartAge()-age == temp){
                                needUnlockProjectList.add(i);
                            }
                        }
                    }
                }
            }
        }
        if(!CollectionUtils.isEmpty(needUnlockProjectList)){
            StringBuffer sql =new StringBuffer();
            int i = 1;
            for (Integration integration : needUnlockProjectList) {
                if (i == needUnlockProjectList.size()) {
                    sql.append("(" + IdWorker.getId() + ",\"" + childId + "\",\"" + integration.getCode() + "\",\"" + integration.getName() + "\",1,0,\"systemInit\",now())");
                } else {
                    sql.append("(" + IdWorker.getId() + ",\"" + childId + "\",\"" + integration.getCode() + "\",\"" + integration.getName() + "\",1,0,\"systemInit\",now()),");
                    i++;
                }
            }
            if (sql != null) {
                this.childProjectConfigMapper.batchInsert(sql.toString());
            }
        }
    }

    @Override
    public boolean hasCheckTrainPackage(Long childCourseId) {
        //判断是否需要选择训练包,
        ChildCourse childCourse = this.childCourseMapper.hasCheckTrainPackage(childCourseId);
        String projects = redisTemplate.opsForValue().get(childCourse.getClassId() + ":7" + "_project");
        if (childCourse.getClassPlanId() == null && StringUtils.isEmpty(projects)) {
            return true;
        }
        if (childCourse.getClassPlanId() == null) {
            JSONObject object = JSONObject.parseObject(projects);
            this.childCourseMapper.updateClassPlanId(childCourseId, Long.valueOf(object.get("classPlanId").toString()));
        }
        return false;
    }

    @Override
    public boolean hasCheckTrainTheme(Long childCourseId) {
        //判断是否需要选择训练主题
//        ChildCourse childCourse = this.childCourseMapper.hasCheckTrainPackage(childCourseId);
//        String projects = redisTemplate.opsForValue().get("theme:"+childCourse.getClassId() );
//        if (childCourse.getClassPlanId() == null && StringUtils.isEmpty(projects)) {
//            return true;
//        }
//        if (childCourse.getClassPlanId() == null) {
//            JSONObject object = JSONObject.parseObject(projects);
//            List<Integer> classList =(List<Integer>) object.get("classTimes");
//            //判断本班级今天有没有已备课课程
//            //若集训班每天两节运动力课在按照课表出项目；若每天仅一节课则选择用每天的第一节课，即第1、3、5、7、9节课。
//            int count= this.childCourseMapper.countPreparedClassId(childCourse.getClassId(),childCourse.getDayDate());
//            int tempClassTimes =classList.size()>0?classList.get(0):0;
//            if(count<=0 && tempClassTimes%2==0){
//                classList.remove(0);
//            }
//            if(classList.size()>0){
//                this.childCourseMapper.updateClassPlanId(childCourseId, Long.valueOf(object.get("classPlanId").toString()));
//            }else {
//                redisTemplate.delete("theme:"+childCourse.getClassId());
//                return true;
//            }
//        }
//        return false;
        ChildCourse local = this.childCourseMapper.selectById(childCourseId);
        if (local.getClassPlanId() != null) {
            return false;
        }
        //获取本班级上一节课主题ID及calssTimes
        ChildCourse lastCourse = this.childCourseMapper.getLastClassInfo(local.getClassId());
        //没有上节课 或 上节课已经是主题内最后一个计划 需要新选主题
        if(lastCourse ==null || lastCourse.getClassTimes()>=lastCourse.getTotalClassTimes()){
            return true;
        }
        //上节课不是当天时 选到9 也要新选
        if(!lastCourse.getDayDate().equals(local.getDayDate()) && lastCourse.getClassTimes() >=9){
            return true;
        }
        int tempClassTimes =0;
        if(!lastCourse.getDayDate().equals(local.getDayDate()) && lastCourse.getClassTimes()%2==1){
            tempClassTimes = lastCourse.getClassTimes()+2;
        }
        if(!lastCourse.getDayDate().equals(local.getDayDate()) && lastCourse.getClassTimes()%2==0){
            tempClassTimes = lastCourse.getClassTimes()+1;
        }
        if(lastCourse.getDayDate().equals(local.getDayDate())){
            tempClassTimes = lastCourse.getClassTimes()+1;
        }
        this.childCourseMapper.updateClassPlanIdAndClassTimes(childCourseId,lastCourse.getClassPlanId(),tempClassTimes);
        return false;
    }

    /**
     * 判断是否能备课，需满足条件：
     * 1、当天此时间点前是否含有未备课课程，需按时间顺序依次备课。
     * 2、前一天之前是否含有已备课且未填成绩课程，需要之前都已填入成绩才可以备课
     *
     * @param childCourseId
     * @return
     */
    @Override
    public Map checkPrepare(Long childCourseId) {
        ChildCourse local = childCourseMapper.selectById(childCourseId);
        Map result = new HashMap();
        result.put("prepare", true);
        if (local != null && local.getPrepareStatus().equals(1)&&local.getScoreFlag().equals(0)) {
            return result;
        }
        String str = checkCourseAllTips(local);
        if(str !=""){
            result.put("prepare", false);
            result.put("msg", str);
            return result;
        }
        return result;
    }

    @Override
    public String checkCourse(ChildCourse local) {
//        String result ="";
//        if (DateUtils.parseDate(local.getDayDate() + " " + local.getEndTime()).before(DateUtils.getNowDate())) {
//            result ="课程过期，无法备课！";
//            return result;
//        }
//
//        if (local.getScoreFlag().equals(1)) {
//            result ="已提交成绩课程无法备课。";
//            return result;
//        }
//        //同一天课程不需要成绩录入可以按顺序直接备课，前一天必须填写成绩
//        ChildCourse childCourse = this.childCourseMapper.getNoScoreByPrepare(local.getId());
//        if (childCourse != null) {
//            result="请先完成："+childCourse.getDayDate() + " " + childCourse.getStartTime() + "-" + childCourse.getEndTime() +childCourse.getTeacherName()+"老师  " +  "课程的成绩录入提交。";
//
//            return result;
//        }
//        //判断班级内学员有无历史未填成绩课程
//        List<ChildCourse> childCourseList = this.childCourseMapper.getNoScoreChild(local.getId(),local.getDayDate());
//        if (!CollectionUtils.isEmpty(childCourseList)) {
//            for(ChildCourse c:childCourseList){
//                result +="请先完成：学员 " +c.getChildNames()+" "+ c.getDayDate() + " " + c.getStartTime() + "-" + c.getEndTime()+" "+c.getTeacherName()+"老师 " + "课程的成绩录入提交。<br>";
//            }
//        }
//        //当前课程之后是否有已完成备课的课程
//        childCourse = this.childCourseMapper.getAfterPrepare(local.getId());
//        if (childCourse != null) {
//            result=childCourse.getDayDate() + " " + childCourse.getStartTime() + "-" + childCourse.getEndTime()+" "+childCourse.getTeacherName()+"老师 " + "课程已经备课，请先做取消备课操作。";
//            return result;
//        }
//        //之前时间未到下课时间，且未备课(上一节课未备课)；
//        childCourse = this.childCourseMapper.getNoPrepare(local.getId());
//        if (childCourse != null) {
//            result="请先完成："+  childCourse.getDayDate() + " " + childCourse.getStartTime() + "-" + childCourse.getEndTime()+" "+childCourse.getTeacherName()+"老师 "  + "课程的备课。";
//            return result;
//        }
//        return result;
        String result ="";
        if (DateUtils.parseDate(local.getDayDate() + " " + local.getEndTime()).before(DateUtils.getNowDate())) {
            result +="课程过期，无法备课！<br>";
        }

        if (local.getScoreFlag().equals(1)) {
            result+="已提交成绩课程无法备课。<br>";
        }
        //同一天课程不需要成绩录入可以按顺序直接备课，前一天必须填写成绩
        ChildCourse childCourse = this.childCourseMapper.getNoScoreByPrepare(local.getId());
        if (childCourse != null) {
            result+="请先完成："+childCourse.getDayDate() + " " + childCourse.getStartTime() + "-" + childCourse.getEndTime() +childCourse.getTeacherName()+"老师  " +  "课程的成绩录入提交。<br>";
        }
        //判断班级内学员有无历史未填成绩课程
        List<ChildCourse> childCourseList = this.childCourseMapper.getNoScoreChild(local.getId(),local.getDayDate(),local.getCourseId());
        if (!CollectionUtils.isEmpty(childCourseList)) {
            for(ChildCourse c:childCourseList){
                result +="请先完成：学员 " +c.getChildNames()+" "+ c.getDayDate() + " " + c.getStartTime() + "-" + c.getEndTime()+" "+c.getTeacherName()+"老师 " + "课程的成绩录入提交。<br>";
            }
        }
        //当前课程之后是否有已完成备课的课程
        childCourse = this.childCourseMapper.getAfterPrepare(local.getId());
        if (childCourse != null) {
            result=childCourse.getDayDate() + " " + childCourse.getStartTime() + "-" + childCourse.getEndTime()+" "+childCourse.getTeacherName()+"老师 " + "课程已经备课，请先做取消备课操作。<br>";
        }
        //之前时间未到下课时间，且未备课(上一节课未备课)；
        childCourse = this.childCourseMapper.getNoPrepare(local.getId());
        if (childCourse != null) {
            result+="请先完成："+  childCourse.getDayDate() + " " + childCourse.getStartTime() + "-" + childCourse.getEndTime()+" "+childCourse.getTeacherName()+"老师 "  + "课程的备课。<br>";
        }
        return result;
    }
    private String checkCourseAllTips(ChildCourse local) {
        String result ="";
        if (DateUtils.parseDate(local.getDayDate() + " " + local.getEndTime()).before(DateUtils.getNowDate())) {
            result +="课程过期，无法备课！<br>";
        }

        if (local.getScoreFlag().equals(1)) {
            result+="已提交成绩课程无法备课。<br>";
        }
        //同一天课程不需要成绩录入可以按顺序直接备课，前一天必须填写成绩
        ChildCourse childCourse = this.childCourseMapper.getNoScoreByPrepare(local.getId());
        if (childCourse != null) {
            result+="请先完成："+childCourse.getDayDate() + " " + childCourse.getStartTime() + "-" + childCourse.getEndTime() +childCourse.getTeacherName()+"老师  " +  "课程的成绩录入提交。<br>";
        }
        //判断班级内学员有无历史未填成绩课程
        List<ChildCourse> childCourseList = this.childCourseMapper.getNoScoreChild(local.getId(),local.getDayDate(),local.getCourseId());
        if (!CollectionUtils.isEmpty(childCourseList)) {
            for(ChildCourse c:childCourseList){
                result +="请先完成：学员 " +c.getChildNames()+" "+ c.getDayDate() + " " + c.getStartTime() + "-" + c.getEndTime()+" "+c.getTeacherName()+"老师 " + "课程的成绩录入提交。<br>";
            }
        }
//        //当前课程之后是否有已完成备课的课程
//        childCourse = this.childCourseMapper.getAfterPrepare(local.getId());
//        if (childCourse != null) {
//            result=childCourse.getDayDate() + " " + childCourse.getStartTime() + "-" + childCourse.getEndTime()+" "+childCourse.getTeacherName()+"老师 " + "课程已经备课，请先做取消备课操作。<br>";
//        }
        //之前时间未到下课时间，且未备课(上一节课未备课)；
        childCourse = this.childCourseMapper.getNoPrepare(local.getId());
        if (childCourse != null) {
            result+="请先完成："+  childCourse.getDayDate() + " " + childCourse.getStartTime() + "-" + childCourse.getEndTime()+" "+childCourse.getTeacherName()+"老师 "  + "课程的备课。<br>";
        }
        return result;
    }

    private String checkCourseNewChild(ChildCourse local) {
        String result="";

        return result;
    }

    @Override
    public Map checkCancelPrepare(Long childCourseId) {
        ChildCourse current = childCourseMapper.selectById(childCourseId);
        Map result = new HashMap();
        result.put("prepare", true);
        if (current != null && current.getScoreFlag().equals(1)) {
            result.put("prepare", false);
            result.put("msg", "成绩已提交，不可取消。");
            return result;
        }
        ChildCourse local = childCourseMapper.getPrepareNoScore(childCourseId);
        if (local != null) {
            result.put("prepare", false);
            result.put("msg", "请先完成：" + local.getDayDate() + " " + local.getStartTime() + "-" + local.getEndTime() + "课程取消备课。");
            return result;
        }
        return result;
    }

    @Override
    public Map checkEnterScore(Long childCourseId) {
        Map result = new HashMap();
        result.put("prepare", true);
        //之前时间是否还有未填成绩课程
        ChildCourse local = this.childCourseMapper.selectById(childCourseId);
        if (DateUtils.parseDate(local.getDayDate() + " " + local.getStartTime()).after(DateUtils.getNowDate())) {
            result.put("prepare", false);
            result.put("msg", "课程未开始，无法录入成绩。");
            return result;
        }

        //本节课是否完成备课
        local = this.childCourseMapper.selectById(childCourseId);
        if (local != null && !local.getPrepareStatus().equals(1)) {
            result.put("prepare", false);
            result.put("msg", "请先完成备课");
            return result;
        }
        if (!local.getPrepareStatus().equals(1) && DateUtils.parseDate(local.getDayDate() + " " + local.getEndTime()).before(DateUtils.getNowDate())) {
            result.put("prepare", false);
            result.put("msg", "课程过期，无法录入成绩。");
            return result;
        }
        ChildCourse childCourse = this.childCourseMapper.getNoScore(childCourseId);
        if (childCourse != null) {
            result.put("prepare", false);
            result.put("msg", "请先完成： "+childCourse.getTeacherName()+"老师，" +  childCourse.getDayDate() + " " + childCourse.getStartTime() + "-" + childCourse.getEndTime() + "课程的成绩录入。");
            return result;
        }
        return result;
    }

    @Override
    public void saveTrainPackage(ChildCourseDTO dto,String loginName) {
        ChildCourse childCourse = this.childCourseMapper.selectById(dto.getChildCourseId());
        childCourse.setClassPlanId(dto.getClassPlanId());
        this.childCourseMapper.updateClassPlanId(dto.getChildCourseId(), dto.getClassPlanId());
        if (dto.getProjectCode().indexOf("|") > -1) {
            String[] projects = dto.getProjectCode().split("\\|");
            JSONObject map = new JSONObject();
            map.put("project", projects[0]);
            map.put("classPlanId", dto.getClassPlanId().toString());
            map.put("count", "0");
            redisTemplate.opsForValue().set(childCourse.getClassId() + ":6" + "_project", map.toJSONString());
            map.put("project", projects[1]);
            redisTemplate.opsForValue().set(childCourse.getClassId() + ":7" + "_project", map.toJSONString());
        } else {
            JSONObject map = new JSONObject();
            map.put("project", dto.getProjectCode());
            map.put("classPlanId", dto.getClassPlanId().toString());
            map.put("count", "0");
            redisTemplate.opsForValue().set(childCourse.getClassId() + ":7" + "_project", map.toJSONString());
        }
        //保存此班级选择训练包记录
        CourseTrainPackage courseTrainPackage = new CourseTrainPackage();
        courseTrainPackage.setClassId(childCourse.getClassId());
        courseTrainPackage.setChildCourseId(childCourse.getId());
        courseTrainPackage.setTrainPackageId(dto.getTrainPackageId());
        courseTrainPackage.setTrainPackageProjectId(dto.getTrainPackageProjectId());
        courseTrainPackage.setCreateTime(DateUtils.getNowDate());
        courseTrainPackage.setCreateUser(loginName);
        this.courseTrainPackageMapper.insert(courseTrainPackage);
    }

    @Override
    public void saveTrainTheme(ChildCourseDTO dto, String loginName) {
        ClassPlan classPlan = this.classPlanMapper.selectById(dto.getClassPlanId());
        ChildCourse childCourse = this.childCourseMapper.selectById(dto.getChildCourseId());
        childCourse.setClassPlanId(dto.getClassPlanId());
        this.childCourseMapper.updateClassPlanIdAndClassTimes(dto.getChildCourseId(), dto.getClassPlanId(),1);
//        JSONObject map = new JSONObject();
//        map.put("classPlanId", dto.getClassPlanId().toString());
//        map.put("count", "0");
//        if(classPlan !=null && classPlan.getTotalClassTimes()!=null){
//            List<Integer> temp = new ArrayList<>();
//            for(int i=1;i<=classPlan.getTotalClassTimes();i++){
//                temp.add(i);
//            }
//            map.put("classTimes", temp);
//        }
//        redisTemplate.opsForValue().set("theme:"+childCourse.getClassId(),map.toJSONString());
        CourseTrainPackage courseTrainPackage =new CourseTrainPackage();
        courseTrainPackage.setClassId(childCourse.getClassId());
        courseTrainPackage.setClassPlanId(Long.valueOf(classPlan.getId()));
        courseTrainPackage.setChildCourseId(childCourse.getId());
        courseTrainPackage.setStatus(0);
        courseTrainPackage.setCreateTime(DateUtils.getNowDate());
        this.courseTrainPackageMapper.insert(courseTrainPackage);

    }

    @Override
    public String printScoreRecord(Long childCourseId) {
        Map result = new HashMap();
        ChildCourse childCourse = this.childCourseMapper.selectById(childCourseId);
        result.put("dayDate", childCourse.getDayDate());
        result.put("weekDay", DateUtils.getWeekDay(DateUtils.parseDate(childCourse.getDayDate())));
        result.put("classTime", childCourse.getStartTime() + "-" + childCourse.getEndTime());
        result.put("teacherName", childCourse.getTeacherName());
        List<CourseChildScoreDTO> list = getData(childCourseId);
        result.put("childList1", new ArrayList<>());
        result.put("childList2", new ArrayList<>());
        result.put("childList3", new ArrayList<>());
        if (list.size() > 0) {
            for (int i = 0; i <= list.size() / 6; i++) {
                if (list.size() >= i * 6 + 6) {
                    result.put("childList" + (i + 1), list.subList(i * 6, i * 6 + 6));
                } else {
                    result.put("childList" + (i + 1), list.subList(i * 6, list.size()));
                }
            }

        }

        String dest = null;
        String templateName = "scoreRecord.html";
        try {
            String fileName = "成绩记录表("+childCourse.getTeacherName()+"_"+childCourse.getDayDate()+"_"+childCourse.getStartTime().replace(":","")+")";
            dest = HtmlToPdf1Utils.toPdf(result, templateName, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        File file = new File(dest);
        //保存报告到oss
        String fileUrl = null;
        try {
            String fileName = file.getName();
            fileUrl = aliOssHandle.upload(fileName, null, new FileInputStream(file));
        } catch (FileNotFoundException e) {
            throw new BusinessException(e.getMessage());
        }
        return fileUrl;
    }

    private List<CourseChildScoreDTO> getData(Long childCourseId) {

        List<CourseChildScoreDTO> list = this.courseChildScoreMapper.findListByCourse(childCourseId);
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        //获取项目记录项
        List<Integer> temp = new ArrayList<>();
        temp.add(4);
        temp.add(4);
        List<Integration> integrationList = integrationMapper.findList(temp);
        Map<String, String> integrationNameMap = new HashMap<>();
        Map<String, String> integrationQuestionMap = new HashMap<>();
        for (Integration i : integrationList) {
            integrationNameMap.put(i.getCode(), i.getName());
            if (i.getQuestions().indexOf("select") > -1) {
                JSONArray array = JSONArray.parseArray(i.getQuestions());
                int index = 0;
                for (Object obj : array) {
                    JSONObject json = JSONObject.parseObject(obj.toString());
                    if (json.get("type").equals("select")) {
                        JSONArray arr1 = JSONArray.parseArray(json.get("option").toString());
                        String str = "";
                        for (Object obj1 : arr1) {
                            JSONObject json1 = JSONObject.parseObject(obj1.toString());
                            str += (str == "" ? json1.get("text") : ("/" + json1.get("text")));
                        }
                        json.put("lable", str);
                        array.set(index, json);
                    }
                    index++;
                }
                i.setQuestions(array.toString());
            }
            //大滑板特殊处理
            if (i.getCode().indexOf(ProjectCodeConstant.大滑板类) > -1) {
                JSONArray newArray = new JSONArray();
                String lableStr = "";
                JSONObject bzJson = new JSONObject();
                JSONArray array = JSONArray.parseArray(i.getQuestions());
                for (Object obj : array) {
                    JSONObject json = JSONObject.parseObject(obj.toString());
                    if (json.get("type").equals("select")) {
                        newArray.add(json);
                    } else if (json.get("key").equals("bz")) {
                        bzJson = json;
                    } else {
                        lableStr += lableStr == "" ? json.get("lable").toString() : ("/" + json.get("lable").toString());
                    }
                }
                JSONObject tempJson = new JSONObject();
                tempJson.put("type", "select");
                tempJson.put("lable", lableStr);
                newArray.add(tempJson);
                newArray.add(bzJson);
                i.setQuestions(newArray.toString());

            }
            integrationQuestionMap.put(i.getCode(), i.getQuestions());
        }
        List<IntegrationTrainAmount> integrationTrainAmountList = this.integrationTrainAmountMapper.listByIds(CollectionUtils.arrayToList(list.get(0).getTrainAmountIds().split(",")));
        Map<String, String> trainAmountNameMap = new HashMap<>();
        for (IntegrationTrainAmount it : integrationTrainAmountList) {
            trainAmountNameMap.put(it.getId().toString(), it.getTrainContent());
        }
        //获取历史成绩
        Map<String, String> scoreMap = new HashMap<>();
        //当节课填写记录
        List<CourseChildScore> scoreList = this.courseChildScoreMapper.selectList(childCourseId);
        for (CourseChildScore score : scoreList) {
            scoreMap.put(score.getChildId() + "-" + score.getProjectCode(), score.getScore());
        }

        for (CourseChildScoreDTO dto : list) {
            dto.setLinkOneQuestionList(JSONArray.parseArray(integrationQuestionMap.get(dto.getLinkOne())));
            dto.setLinkTwoQuestionList(JSONArray.parseArray(integrationQuestionMap.get(dto.getLinkTwo())));
            dto.setLinkThreeQuestionList(JSONArray.parseArray(integrationQuestionMap.get(dto.getLinkThree())));
            dto.setLinkFourQuestionList(JSONArray.parseArray(integrationQuestionMap.get(dto.getLinkFour())));
            dto.setLinkFiveQuestionList(JSONArray.parseArray(integrationQuestionMap.get(dto.getLinkFive())));
            dto.setLinkSixQuestionList(JSONArray.parseArray(integrationQuestionMap.get(dto.getLinkSix())));
            dto.setLinkSevenQuestionList(JSONArray.parseArray(integrationQuestionMap.get(dto.getLinkSeven())));
            dto.setLinkEightQuestionList(JSONArray.parseArray(integrationQuestionMap.get(dto.getLinkEight())));
            dto.setLinkNineQuestionList(JSONArray.parseArray(integrationQuestionMap.get(dto.getLinkNine())));

            dto.setLinkOne(StringUtils.isEmpty(dto.getLinkOne()) ? "" : (integrationNameMap.get(dto.getLinkOne()) + (StringUtils.isEmpty(dto.getTrainAmountOne()) ? "" : "/" + trainAmountNameMap.get(dto.getTrainAmountOne()))));
            dto.setLinkTwo(StringUtils.isEmpty(dto.getLinkTwo()) ? "" : (integrationNameMap.get(dto.getLinkTwo()) + (StringUtils.isEmpty(dto.getTrainAmountTwo()) ? "" : "/" + trainAmountNameMap.get(dto.getTrainAmountTwo()))));
            dto.setLinkThree(StringUtils.isEmpty(dto.getLinkThree()) ? "" : (integrationNameMap.get(dto.getLinkThree()) + (StringUtils.isEmpty(dto.getTrainAmountThree()) ? "" : "/" + trainAmountNameMap.get(dto.getTrainAmountThree()))));
            dto.setLinkFour(StringUtils.isEmpty(dto.getLinkFour()) ? "" : (integrationNameMap.get(dto.getLinkFour()) + (StringUtils.isEmpty(dto.getTrainAmountFour()) ? "" : "/" + trainAmountNameMap.get(dto.getTrainAmountFour()))));
            dto.setLinkFive(StringUtils.isEmpty(dto.getLinkFive()) ? "" : (integrationNameMap.get(dto.getLinkFive()) + (StringUtils.isEmpty(dto.getTrainAmountFive()) ? "" : "/" + trainAmountNameMap.get(dto.getTrainAmountFive()))));
            dto.setLinkSix(StringUtils.isEmpty(dto.getLinkSix()) ? "" : (integrationNameMap.get(dto.getLinkSix()) + (StringUtils.isEmpty(dto.getTrainAmountSix()) ? "" : "/" + trainAmountNameMap.get(dto.getTrainAmountSix()))));
            dto.setLinkSeven(StringUtils.isEmpty(dto.getLinkSeven()) ? "" : (integrationNameMap.get(dto.getLinkSeven()) + (StringUtils.isEmpty(dto.getTrainAmountSeven()) ? "" : "/" + trainAmountNameMap.get(dto.getTrainAmountSeven()))));
            dto.setLinkEight(StringUtils.isEmpty(dto.getLinkEight()) ? "" : (integrationNameMap.get(dto.getLinkEight()) + (StringUtils.isEmpty(dto.getTrainAmountEight()) ? "" : "/" + trainAmountNameMap.get(dto.getTrainAmountEight()))));
            dto.setLinkNine(StringUtils.isEmpty(dto.getLinkNine()) ? "" : (integrationNameMap.get(dto.getLinkNine()) + (StringUtils.isEmpty(dto.getTrainAmountNine()) ? "" : "/" + trainAmountNameMap.get(dto.getTrainAmountNine()))));
        }
        return list;

    }

    @Override
    public Map checkTrainPackage(Long childCourseId, String loginUserName) {
        //判断训练包环节是否有项目,
        ChildCourse childCourseTemp = this.childCourseMapper.hasCheckTrainPackage(childCourseId);
        String projects = redisTemplate.opsForValue().get(childCourseTemp.getClassId() + ":7" + "_project");
        if (childCourseTemp.getClassPlanId() != null && null != projects && projects != "") {
            return null;
        }
        ChildCourseDTO dto = new ChildCourseDTO();
        ChildCourse completeCourse = this.childCourseMapper.getCompleteTimes(childCourseId);
        ChildCourse currentCourse = this.childCourseMapper.selectById(childCourseId);
        dto.setAgeGrade(currentCourse.getAgeGrade());
        dto.setClassType(currentCourse.getClassType());
        dto.setCourseId(Integer.valueOf(currentCourse.getCourseId()));
        String classPlanSortTemp = "";
        if (completeCourse == null) {
            String classSort= this.classPlanSortMapper.getClassPlanSort(currentCourse.getClassId());
            if(StringUtils.isEmpty(classSort)){
                classPlanSortTemp = DictUtils.getDictValue("class_plan_sort", String.valueOf(DateUtils.getYear(new Date()) % 2));
                dto.setClassPlanSort(classPlanSortTemp);
                ClassPlanSort classPlanSort = new ClassPlanSort();
                classPlanSort.setId(IdWorker.getId());
                classPlanSort.setClassPlanSort(classPlanSortTemp);
                classPlanSort.setClassPlanSort(classPlanSortTemp);
                classPlanSort.setClassId(currentCourse.getClassId());
                classPlanSort.setCreateTime(DateUtils.getNowDate());
                classPlanSort.setCreateUser(loginUserName);
                this.classPlanSortMapper.insert(classPlanSort);
            }
            completeCourse = new ChildCourse();
            completeCourse.setClassTimes(0);
            completeCourse.setClassId(currentCourse.getClassId());
        }
        //3、按照该班级的年计划顺序获取训练计划list
        List<ClassPlan> classPlanList = classPlanMapper.getClassPlan(dto);
        int totalClass = 0;
        Long reqClassPlanId = null;
        int reqClassTimes = 0;
        for (int i = 0; i < classPlanList.size(); i++) {//匹配对应课次的训练计划id 和课次
            totalClass += classPlanList.get(i).getTotalClassTimes();
        }
        if (completeCourse.getClassTimes() > 0) {
            completeCourse.setClassTimes(completeCourse.getClassTimes() % totalClass);
        }
        for (int i = 0; i < classPlanList.size(); i++) {//匹配对应课次的训练计划id 和课次
            if (completeCourse.getClassTimes() + 1 <= classPlanList.get(i).getTotalClassTimes()) {
                reqClassPlanId = Long.valueOf(classPlanList.get(i).getId());
                reqClassTimes = completeCourse.getClassTimes() + 1;
                break;
            } else {
                completeCourse.setClassTimes(completeCourse.getClassTimes() - classPlanList.get(i).getTotalClassTimes());
            }
        }
        //获取符合训练计划的各环节项目
        List<ClassPlanDetail> classPlanDetailList = this.classPlanDetailMapper.findList(reqClassPlanId, reqClassTimes);
        List<String> ids = new ArrayList<>();
        for (ClassPlanDetail c : classPlanDetailList) {
            if (c.getLinkRuleType() == 2 && c.getTrainPackageId() != null) {
                ids.addAll(CollectionUtils.arrayToList(c.getTrainPackageId().split(",")));
            }
        }
        List<TrainPackageDTO> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(ids)) {
            list = this.trainPackageMapper.findListByIds(ids, completeCourse.getClassId());
        }
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("childCourseId", childCourseId.toString());
        result.put("classPlanId", reqClassPlanId.toString());
        result.put("classTimes", reqClassTimes);
        return result;
    }

    @Override
    public Map getCheckTrainTheme(Long childCourseId, String loginUserName) {
        //判断训练包环节是否有项目,
        ChildCourse childCourse = this.childCourseMapper.selectById(childCourseId);
        List<ClassPlan> list = this.classPlanMapper.selectThemeList(childCourse.getAgeGrade(),childCourse.getClassType(),childCourse.getClassId(),childCourse.getCourseId());
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("childCourseId", childCourseId.toString());
        return result;
    }

    @Override
    public void completePrepare(Long childCourseId) {
        ChildCourse childCourse = this.childCourseMapper.selectById(childCourseId);
        if (childCourse != null && childCourse.getPrepareStatus().equals(0)) {
            String project6 = redisTemplate.opsForValue().get(childCourse.getClassId() + ":6" + "_project");
            if (StringUtils.isNotEmpty(project6)) {
                JSONObject object = JSONObject.parseObject(project6);
                List<String> projectList6 = StringUtils.split2List(StringUtils.getString(object.get("project")), ',');
                if (projectList6.size() > 0) {
                    projectList6.remove(0);
                    object.put("project", StringUtils.list2String(projectList6, ","));
                    if(projectList6.size()>0){
                        redisTemplate.opsForValue().set(childCourse.getClassId() + ":6" + "_project", object.toJSONString());
                    }else {
                        redisTemplate.delete(childCourse.getClassId() + ":6" + "_project");
                    }
                }

            }
            String project7 = redisTemplate.opsForValue().get(childCourse.getClassId() + ":7" + "_project");
            if (StringUtils.isNotEmpty(project7)) {
                JSONObject object = JSONObject.parseObject(project7);
                List<String> projectList7 = StringUtils.split2List(StringUtils.getString(object.get("project")), ',');
                if (projectList7.size() > 0) {
                    projectList7.remove(0);
                    object.put("project", StringUtils.list2String(projectList7, ","));
                    if(projectList7.size() > 0){
                        redisTemplate.opsForValue().set(childCourse.getClassId() + ":7" + "_project", object.toJSONString());
                    }else {
                        redisTemplate.delete(childCourse.getClassId() + ":7" + "_project");
                    }
                }
            }
            this.childCourseMapper.updatePrepareStatus(childCourseId, 1);
//            Map map =new HashMap<>();
//            map.put("scheduleId",childCourse.getId());
//            map.put("prepareStatus",1);
//            this.sender.sender(map);
        }
    }

    @Override
    public void savePlan(Long id, Long classPlanId,Integer classTimes) {
        this.childCourseMapper.savePlan(id,classPlanId,classTimes);
    }

    @Override
    public void saveFusionPlan(Long classId, Integer classTimes, Long classPlanId) {
        this.childCourseMapper.saveFusionPlan(classId,classTimes,classPlanId);

    }

    @Override
    public void cancelPlan(Long id) {
        this.childCourseMapper.cancelPlan(id);
    }

    @Override
    public void notClass(Long childCourseId) {
        ChildCourse childCourse =this.childCourseMapper.selectById(childCourseId);
        //判断当前课程之后是否有已备课课程
        int total = this.childCourseMapper.countPreparedCourse(childCourseId);
        if (total <= 0) {
            returnTrainPackage(childCourseId);
        }
        this.childCourseMapper.updatePrepareStatus(childCourseId, 2);
        this.courseChildProjectMapper.cancelPrepare(childCourseId);
        //删除当前课程之前未备课且已生成项目的记录
        this.courseChildProjectMapper.delProject(childCourse.getClassId(),childCourse.getDayDate()+" "+childCourse.getStartTime());

//        ChildCourse childCourse = this.childCourseMapper.selectById(childCourseId);
//        Map map =new HashMap<>();
//        map.put("scheduleId",childCourse.getId());
//        map.put("prepareStatus",2);
//        this.sender.sender(map);

    }

    @Override
    public Map checkNotClass(Long childCourseId) {
        ChildCourse local = childCourseMapper.selectById(childCourseId);
        Map result = new HashMap();
        result.put("prepare", true);
        if (local != null && local.getScoreFlag().equals(1)) {
            result.put("prepare", false);
            result.put("msg", "成绩已提交，不可操作未上课。");
            return result;
        }
        return result;
    }

    /**
     * 取消备课
     * 当取消时，下一节课已备课：此节课训练包项目跳过，不再训练
     * 当取消时，下一节课未备课：此节课训练包项目不跳过，放回redis，下一节课继续训练,当训练包满5个重新选择
     * * @param childCourseId
     */
    @Override
    public void cancelPrepare(Long childCourseId) {
        //判断当前课程之后是否有已备课课程
        int total = this.childCourseMapper.countPreparedCourse(childCourseId);
        if (total <= 0) {
            returnTrainPackage(childCourseId);
        }
        this.childCourseMapper.cancelPrepare(childCourseId);
        this.courseChildProjectMapper.cancelPrepare(childCourseId);
        ChildCourse childCourse = this.childCourseMapper.selectById(childCourseId);
        //删除当前课程之后未备课且已生成项目的记录、以及课程表class_plan_id
        this.courseChildProjectMapper.delProject(childCourse.getClassId(),childCourse.getDayDate()+" "+childCourse.getStartTime());
        this.childCourseMapper.delClassPlanId(childCourse.getClassId(),childCourse.getDayDate()+" "+childCourse.getStartTime());
        //删除选择训练包记录
        this.courseTrainPackageMapper.updateByClass(childCourse.getClassId(),childCourse.getId());


//        Map map =new HashMap<>();
//        map.put("scheduleId",childCourse.getId());
//        map.put("prepareStatus",0);
//        this.sender.sender(map);
    }

    /**
     * 训练包项目放回训练池子
     *
     * @param childCourseId
     */
    private void returnTrainPackage(Long childCourseId) {
        ChildCourse childCourse = this.childCourseMapper.selectById(childCourseId);
        //classType:1常规班，2集训班
        if(childCourse.getClassType().equals(1)) {
            CourseChildProject project = this.courseChildProjectMapper.getTrainPackageProject(childCourseId);
            if (childCourse != null && project != null) {
                //3-4岁环节6也是训练包需要放回redis
                if (StringUtils.isNotEmpty(project.getInitSix())) {
                    String project6 = redisTemplate.opsForValue().get(childCourse.getClassId() + ":6" + "_project");
                    if (StringUtils.isNotEmpty(project6)) {
                        JSONObject object = JSONObject.parseObject(project6);
                        List<String> projectList6 = StringUtils.split2List(StringUtils.getString(object.get("project")), ',');
                        if (projectList6.size() == 4) {
                            redisTemplate.delete(childCourse.getClassId() + ":6" + "_project");
                            this.courseTrainPackageMapper.updateByClass(childCourse.getClassId(), childCourseId);
                        }
                        if (projectList6.size() > 0 && projectList6.size() != 4) {
                            projectList6.add(0, project.getInitSix());
                            object.put("project", StringUtils.list2String(projectList6, ","));
                            redisTemplate.opsForValue().set(childCourse.getClassId() + ":6" + "_project", object.toJSONString());
                        }
                    } else {
                        JSONObject map = new JSONObject();
                        map.put("project", project.getInitSix());
                        map.put("classPlanId", childCourse.getClassPlanId().toString());
                        map.put("count", "0");
                        redisTemplate.opsForValue().set(childCourse.getClassId() + ":6" + "_project", map.toJSONString());

                    }
                }
                //所有年龄段环节7都是训练包项目，需要放回redis
                if (StringUtils.isNotEmpty(project.getInitSeven())) {
                    String project7 = redisTemplate.opsForValue().get(childCourse.getClassId() + ":7" + "_project");
                    if (StringUtils.isNotEmpty(project7)) {
                        JSONObject object = JSONObject.parseObject(project7);
                        List<String> projectList7 = StringUtils.split2List(StringUtils.getString(object.get("project")), ',');
                        if (projectList7.size() == 4) {
                            redisTemplate.delete(childCourse.getClassId() + ":7" + "_project");
                            this.courseTrainPackageMapper.updateByClass(childCourse.getClassId(), childCourseId);
                        }
                        if (projectList7.size() > 0 && projectList7.size() != 4) {
                            projectList7.add(0, project.getInitSeven());
                            object.put("project", StringUtils.list2String(projectList7, ","));
                            redisTemplate.opsForValue().set(childCourse.getClassId() + ":7" + "_project", object.toJSONString());
                        }
                    } else {
                        JSONObject map = new JSONObject();
                        map.put("project", project.getInitSeven());
                        map.put("classPlanId", childCourse.getClassPlanId().toString());
                        map.put("count", "0");
                        redisTemplate.opsForValue().set(childCourse.getClassId() + ":7" + "_project", map.toJSONString());

                    }
                }
            }
        }

        if(childCourse.getClassType().equals(2)){
//            String redisKey = "theme:"+childCourse.getClassId();
//            if(childCourse.getClassTimes().equals(1)){
//                redisTemplate.delete(redisKey);
//                return;
//            }
//            String projects = redisTemplate.opsForValue().get(redisKey);
//            JSONObject object = JSONObject.parseObject(projects);
//            List<Integer> classList =(List<Integer>) object.get("classTimes");
//            classList.set(0,childCourse.getClassTimes());
//            object.put("classTimes",classList);
//            redisTemplate.opsForValue().set(redisKey,object.toJSONString());
        }
    }


    @Override
    public List<Child> listCourseChild(Long childCourseId) {
        return this.courseChildMapper.listCourseChild(childCourseId);
    }

    @Override
    public void replaceInitLink(CourseChildProject project) {
        this.courseChildProjectMapper.update(project);
        //第一次替换增加项目被替换次数
        if (StringUtils.isNotEmpty(project.getCountOldProject())) {
            ChildProjectConfig config = this.childProjectConfigMapper.selectOne(project.getChildId(), project.getCountOldProject());
            if (config == null) {
                config = new ChildProjectConfig();
                config.setId(IdWorker.getId());
                config.setChildId(project.getChildId());
                config.setProjectCode(project.getCountOldProject());
                config.setProjectName(this.integrationService.getCodeName(project.getCountOldProject()));
                config.setReplaceTimes(1);
                config.setStatus(0);
                config.setCreateTime(DateUtils.getNowDate());
                this.childProjectConfigMapper.insert(config);

            } else {
                this.childProjectConfigMapper.addReplaceTimes(project.getChildId(), project.getCountOldProject());
            }
        }
    }

    @Override
    public void replaceDifficulty(CourseChildProject project) {
        if(StringUtils.isNotEmpty(project.getProjectCode())){
            switch (project.getLinkNo()){
                case 1:project.setLinkOne(project.getProjectCode());project.setInitOne(project.getProjectCode());break;
                case 2:project.setLinkTwo(project.getProjectCode());project.setInitTwo(project.getProjectCode());break;
                case 3:project.setLinkThree(project.getProjectCode());project.setInitThree(project.getProjectCode());break;
                case 4:project.setLinkFour(project.getProjectCode());project.setInitFour(project.getProjectCode());break;
                case 5:project.setLinkFive(project.getProjectCode());project.setInitFive(project.getProjectCode());break;
                case 6:project.setLinkSix(project.getProjectCode());project.setInitSix(project.getProjectCode());break;
                case 7:project.setLinkSeven(project.getProjectCode());project.setInitSeven(project.getProjectCode());break;
                case 8:project.setLinkEight(project.getProjectCode());project.setInitEight(project.getProjectCode());break;
                case 9:project.setLinkNine(project.getProjectCode());project.setInitNine(project.getProjectCode());break;
            }
        }
        this.courseChildProjectMapper.update(project);
        //检查学生是否有能力配置
        ChildProjectConfig config = this.childProjectConfigMapper.selectOne(project.getChildId(),project.getProjectCode());
        if(config ==null){
            config =new ChildProjectConfig();
            config.setId(IdWorker.getId());
            config.setChildId(project.getChildId());
            config.setProjectCode(project.getProjectCode());
            config.setProjectName(this.integrationMapper.getCodeName(project.getProjectCode()));
            config.setDifficultyLevel(1);
            config.setStatus(0);
            config.setCreateTime(DateUtils.getNowDate());
            this.childProjectConfigMapper.insert(config);
        }
    }

    @Override
    public Map getProjectCompleteTimes(Long child, List<String> projectCodes) {
        List<ChildProjectConfig> list = this.childProjectConfigMapper.listCompleteTimesByCode(child, projectCodes);
        Map<String, Integer> result = new HashMap<>();
        for (ChildProjectConfig config : list) {
            result.put(config.getProjectCode(), config.getCompleteTimes());
        }
        return result;
    }
}
